const { SuccessModel, ErrorModel } = require('../../utils/index')
const models = require('../../db/mysqldb/index')
const logger = require('./../../utils/logger')

class Users {
  /**
   * 获取用户列表
   * @param {*} req {query:{page = 1, limit = 10 }}
   */
  static async getUserList (req, res) {
    const { page = 1, limit = 10 } = req.query
    logger.info('getUserList', 'req.query', req.query)
    try {
      let { count, rows } = await models.user.findAndCountAll({
        attributes: [
          'uid',
          'nickname',
          'last_sign_time',
          'reg_ip',
          'user_role_ids',
          'ban_dt',
          'enable'
        ],
        where: '',
        offset: (Number(page) - 1) * Number(limit),
        limit: Number(limit)
      })
      for (const key in row) {
        if (row.hasOwnProperty(key)) {
          // 对用户列表数据时间进行格式化
          row[key].ft_ban_dt = await moment(rows[i].ban_dt).format('YYYY年MM月DD日 HH时mm分ss秒')
        }
        // 根据用户列表查找用户信息
        rows[key].user_info = await models.user_info.findOne({
          where: row[ket].uid
        })
      }
      logger.info('getUserList', 'count', count)
      logger.info('getUserList', 'rows', rows)
      res.json(new SuccessModel({ count, rows, page, limit }, 'success'))
    } catch (error) {
      logger.info('getUserList', 'error', error.message)
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * 编辑用户列表
   * @param {*} req {uid, nickname, user_role_ids, enable}
   */
  static async editUser (req, res) {
    const { uid, nickname, user_role_ids, enable } = req.body
    logger.info('editUser', 'req.body', req.body)
    try {
      // 用户更新
      const editRes = await models.user.update({
        nickname: nickname,
        user_role_ids: user_role_ids ? user_role_ids.join(',') : '',
        enable: enable || false
      }, {
        where: {
          uid: uid
        }
      })
      logger.info('editUser', 'editRes', editRes)
      res.json(new SuccessModel([], '更新成功'))
    } catch (error) {
      logger.info('editUser', 'error', error.message)
      res.json(new ErrorModel(error.message))
    }
  }
  /**
   * 删除用户
   * @param {*} req  {body:{uid}}
   */
  static async deleteUser (req, res) {
    const { uid } = req.body
    logger.info('deleteUser', 'req.body', req.body)
    try {
      // 判断用户是否有文章
      let oneArticle = await models.article.findOne({
        where: {
          uid
        }
      })
      logger.info('deleteUser', 'oneArticle', oneArticle)

      if (!oneArticle) {
        // 没有文章 直接删除用户
        const deleteRes = await models.user.destroy({ where: { uid } })
        logger.info('deleteUser', 'deleteRes', deleteRes)
        res.json(new SuccessModel(`删除用户成功`))
      } else {
        // 有文章 传递一个回调函数来启动一个事务
        const deleteRes = await models.sequelize.transaction(transaction => {
          return models.user.destroy({ where: { uid } }, { transaction }).then(
            deleteAdminUser => {
              return models.article.destroy({
                where: { uid }
              }, {
                ...transaction
              })
            }
          )
        })
        logger.info('deleteUser', 'deleteRes', deleteRes)
        res.json(new SuccessModel(`删除用户成功,同时删除用户所有文章`))
      }
    } catch (error) {
      logger.info('deleteUser', 'error', error.message)
      res.json(new ErrorModel(error.message))
    }
  }
  /**
   * 获取用户图片
   * @param {*} req 
   */
  static async getAvatarReview (req, res) {
    const { page = 1, limit = 10, status = 1 } = req.query
    logger.info('getAvatarReview', 'req.query', req.query)
    try {
      let { count, rows } = await models.user_info.findAndCountAll({
        where: {
          avatar_review_status: status
        },
        offset: (Number(page - 1) * Number(limit)),
        limit: Number(limit)
      })
      for (const key in rows) {
        if (rows.hasOwnProperty(key)) {
          rows[key].user = await models.user.findOne({
            where: {
              uid: rows[i].uid
            },
            attributes: [
              'uid', 'avatar', 'nickname', 'sex', 'introduction'
            ]
          })
        }
      }

      logger.info('getAvatarReview', 'count', count)
      logger.info('getAvatarReview', 'rows', rows)

      res.json({ count, rows, page, limit }, 'success')
    } catch (error) {
      logger.info('getAvatarReview', 'error', error.message)
      res.json(new ErrorModel(error.message))
    }
  }
  /**
   * 审核用户图片
   * @param {Object} req {body:{uid, status }}
   */
  static async set_avatar_review (req, res) {
    try {
      // ：1：审核中，2：审核成功，3：审核失败',
      const { uid, status } = req.body
      let oneUserInfo = await models.user_info.findOne({
        where: {
          uid: uid
        }
      })
      logger.info('set_avatar_review', 'oneUserInfo', oneUserInfo)
      if (status === '2') {
        const user_res = await models.user.update({
          avatar: oneUserInfo.avatar_review
        }, {
          where: {
            uid
          }
        })
        const user_info_res = await models.user_info.update(
          {
            avatar_review_status: status
          },
          {
            where: {
              uid: uid // 查询条件
            }
          }
        )
        logger.info('set_avatar_review', 'user_res', user_res)
        logger.info('set_avatar_review', 'user_info_res', user_info_res)
      } else if (status === '3' || status === '1') {
        const user_info_res = await models.user_info.update(
          {
            avatar_review_status: status
          },
          {
            where: {
              uid: uid // 查询条件
            }
          }
        )
        logger.info('set_avatar_review', 'user_info_res', user_info_res)
      }
      res.json(new SuccessModel(`更新成功`))
    } catch (error) {
      logger.info('set_avatar_review', 'error', error.message)
      res.json(new ErrorModel(error.message))
    }
  }
  /**
   * 用户禁言
   * @param {*} req {body:{uid, ban_dt}}
   */
  static async banUser (req, res) {
    try {
      const { uid, ban_dt } = req.body
      logger.info('banUser', 'req.body', req.body)
      let setUpdate = {}
      ban_dt && (setUpdate['ban_dt'] = new Date(ban_dt))
      // 审核成功
      const banRes = await models.user.update(
        {
          ...setUpdate
        },
        {
          where: {
            uid: uid // 查询条件
          }
        }
      )
      logger.info('banUser', 'banRes', banRes)
      res.json(new SuccessModel(`禁言成功`))
    } catch (error) {
      logger.info('banUser', 'error', error.message)
      res.json(new ErrorModel(error.message))
    }
  }
}
module.exports = {
  Users
}